package cn.exrick.xboot.modules.assessment.controller;

import cn.exrick.xboot.base.XbootBaseController;
import cn.exrick.xboot.common.utils.PageUtil;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.vo.PageVo;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.common.vo.SearchVo;
import cn.exrick.xboot.modules.assessment.entity.HkAssessmentIndex;
import cn.exrick.xboot.modules.assessment.entity.HkFormEntity;
import cn.exrick.xboot.modules.assessment.entity.HkFormRelationShip;
import cn.exrick.xboot.modules.assessment.service.HkAssessmentIndexService;
import cn.exrick.xboot.modules.assessment.service.HkFormEntityService;
import cn.exrick.xboot.modules.assessment.service.HkFormRelationShipService;
import cn.exrick.xboot.modules.assessment.to.HkFormEntityTo;
import cn.exrick.xboot.modules.assessment.vo.HkFormEntityVo;
import cn.exrick.xboot.modules.assessment.vo.HkFormResultVo;
import cn.exrick.xboot.modules.content.entity.HontPost;
import cn.exrick.xboot.modules.content.service.HontPostService;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.opencv.presets.opencv_core;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author yck
 */
@Slf4j
@RestController
@Api(description = "表单实体类管理接口")
@RequestMapping("/xboot/hkFormEntity")
@Transactional
public class HkFormEntityController extends XbootBaseController<HkFormEntity, String> {

    @Autowired
    private HkFormEntityService hkFormEntityService;
    @Autowired
    private HkFormRelationShipService hkFormRelationShipService;
    @Autowired
    private HontPostService hontPostService;
    @Autowired
    private HkAssessmentIndexService hkAssessmentIndexService;

    @Override
    public HkFormEntityService getService() {
        return hkFormEntityService;
    }

    @RequestMapping(value = "/getByCondition", method = RequestMethod.GET)
    @ApiOperation(value = "多条件分页获取")
    public Result<Page<HkFormEntity>> getByCondition(HkFormEntity hkFormEntity,
                                                     SearchVo searchVo,
                                                     PageVo pageVo) {
        pageVo.setOrder("asc");
        pageVo.setSort("createTime");
        Page<HkFormEntity> page = hkFormEntityService.findByCondition(hkFormEntity, searchVo, PageUtil.initPage(pageVo));
        for (HkFormEntity hkFormEntity1 : page.getContent()){
            List<HkFormRelationShip> byFormId = hkFormRelationShipService.findByFormId(hkFormEntity1.getId());
            hkFormEntity1.setIndexSize(byFormId.size());
        }
        return new ResultUtil<Page<HkFormEntity>>().setData(page);
    }

    /*@RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "保存数据")
    @Override
    public Result save(HkFormEntity entity) {

        HkFormEntity save = hkFormEntityService.save(entity);
        String[] formItemIds = entity.getFormItemIds();
        for (int i = 0; i < formItemIds.length; i++) {
            HkFormRelationShip ship = new HkFormRelationShip();
            ship.setFormId(save.getId());
            ship.setItemId(formItemIds[i]);
            ship.setSortNumber(i + 1);
            hkFormRelationShipService.save(ship);
        }
        return ResultUtil.success("保存成功！");
    }*/


    /*
     * 重写修改
     * */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改数据")

    public Result updateForm(@RequestBody HkFormEntityVo formEntityVo) {
        List<HkFormEntity> byFromName = hkFormEntityService.findByFromName(formEntityVo.getFormName());
        if (byFromName.size() != 0) {
            for (int i = 0; i < byFromName.size(); i++) {
                if (byFromName.get(i).getFormName().equals(formEntityVo.getFormName()) && byFromName.get(i).getId().equals(formEntityVo.getId())) {
                    hkFormEntityService.updateFormEntity(formEntityVo);
                    return ResultUtil.success("保存成功");
                } else if (byFromName.size() < 1) {
                    hkFormEntityService.updateFormEntity(formEntityVo);
                    return ResultUtil.success("保存成功");
                } else if (!byFromName.get(i).getId().equals(formEntityVo.getId())) {
                    return ResultUtil.error("保存失败，表单名重复！");
                }
            }
        }else {
            hkFormEntityService.updateFormEntity(formEntityVo);
            return ResultUtil.success("修改成功！");
        }

        return ResultUtil.success("修改成功！");
    }


    @RequestMapping(value = "/getFormEntity/{id}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "通过id获取")
    public Result getFormEntity(@PathVariable String id) {
        HkFormEntity hkFormEntity = hkFormEntityService.get(id);
        List<HkFormRelationShip> list = hkFormRelationShipService.getAllByFormId(hkFormEntity.getId());
        String[] itemids = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            itemids[i] = list.get(i).getItemId();
        }
        hkFormEntity.setFormItemIds(itemids);
        return ResultUtil.data(hkFormEntity);
    }

    @RequestMapping(value = "/getAllList", method = RequestMethod.GET)
    @ApiOperation(value = "获取全部表单")
    public Result<List<HkFormEntity>> getAllList() {
        List<HkFormEntity> all = hkFormEntityService.getAll();
        return ResultUtil.data(all);
    }

    @RequestMapping(value = "/getFormEntityById", method = RequestMethod.GET)
    @ApiOperation(value = "通过id获取")
    public Result<HkFormEntity> getFormEntityById(String id) {
        HkFormEntity hkFormEntity = hkFormEntityService.get(id);
        List<HkFormRelationShip> byFormId = hkFormRelationShipService.findByFormId(id);
        if (byFormId.size() == 0){
            return ResultUtil.data(hkFormEntity);
        }
        List<HkAssessmentIndex> assessmentIndexList = new ArrayList<>();
        for (int i = 0; i < byFormId.size(); i++) {
            HkAssessmentIndex byIndexName = hkAssessmentIndexService.get(byFormId.get(i).getItemId());
            byIndexName.setModelName(byFormId.get(i).getModelName());
            byIndexName.setSortNumber(byFormId.get(i).getSortNumber());
            assessmentIndexList.add(byIndexName);
        }
        Map<Integer, List<HkAssessmentIndex>> collect = assessmentIndexList.stream().collect(Collectors.groupingBy(HkAssessmentIndex::getIndexType));
        List<HkFormResultVo> hkFormResultVos  = new ArrayList<>();
        for (Map.Entry<Integer, List<HkAssessmentIndex>> entry : collect.entrySet()) {
            HkFormResultVo hkFormResultVo = new HkFormResultVo();
            hkFormResultVo.setIndexTypeName(entry.getKey());
            hkFormResultVo.setHkAssessmentIndices(entry.getValue());
            hkFormResultVos.add(hkFormResultVo);
        }
        hkFormEntity.setHkFormResultVos(hkFormResultVos);
        return ResultUtil.data(hkFormEntity);
    }
    @RequestMapping(value = "/getAssessmentIndexByIdAndSort", method = RequestMethod.GET)
    @ApiOperation(value = "通过id获取排序后的指标")
    public Result<Object> getAssessmentIndexByIdAndSort(String id) {
        List<HkFormRelationShip> byFormId = hkFormRelationShipService.findByFormId(id);
        List<HkAssessmentIndex> assessmentIndexList = new ArrayList<>();
        for (int i = 0; i < byFormId.size(); i++) {
            HkAssessmentIndex byIndexName = hkAssessmentIndexService.get(byFormId.get(i).getItemId());
            byIndexName.setModelName(byFormId.get(i).getModelName());
            assessmentIndexList.add(byIndexName);
        }
        return ResultUtil.data(assessmentIndexList);
    }


    @RequestMapping(value = "/saveHkForm", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增表单")
    public Result<HkFormEntity> add(@RequestBody HkFormEntityVo formEntityVo) {
        List<HkFormEntity> all = hkFormEntityService.getAll();
        for (int i = 0; i < all.size(); i++) {
            if (all.get(i).getFormName().equals(formEntityVo.getFormName())) {
                return ResultUtil.error("保存失败，表单名重复！");
            }
        }
        HkFormEntity hkFormEntity = new HkFormEntity();
        hkFormEntity.setFormName(formEntityVo.getFormName());
        hkFormEntity.setActTypeId(formEntityVo.getActTypeId());
        hkFormEntity.setActTypeName(formEntityVo.getActTypeName());
        hkFormEntity.setFlowId(formEntityVo.getFlowId());
        hkFormEntity.setFlowName(formEntityVo.getFlowName());
        HkFormEntity save = hkFormEntityService.save(hkFormEntity);
        List<HkFormRelationShip> formRelationShips = formEntityVo.getFormRelationShips();
        for (int i = 0; i < formRelationShips.size(); i++) {
            HkFormRelationShip ship = new HkFormRelationShip();
            ship.setFormId(save.getId());
            ship.setItemId(formRelationShips.get(i).getItemId());
            ship.setModelName(formRelationShips.get(i).getModelName());
            ship.setSortNumber(i + 1);
            hkFormRelationShipService.save(ship);
        }
        return ResultUtil.data(save);
    }


    @RequestMapping(value = "/delFormEntity/{id}", method = RequestMethod.GET)
    @ResponseBody
    @Transactional
    @ApiOperation(value = "通过id删除")
    public Result delFormEntity(@PathVariable String id) {
        HkFormEntity hkFormEntity = hkFormEntityService.get(id);
        if (hkFormEntity != null) {
            List<HkFormRelationShip> list = hkFormRelationShipService.getAllByFormId(hkFormEntity.getId());
            for (int i = 0; i < list.size(); i++) {
                hkFormRelationShipService.delete(list.get(i).getId());
            }
            hkFormEntityService.delete(id);
        }
        return ResultUtil.success("删除成功");
    }

    @RequestMapping(value = "/addVerify", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "保存时校验")
    public Result<Object> verify(String formName) {
        List<HkFormEntity> all = hkFormEntityService.getAll();
        for (int i = 0; i < all.size(); i++) {
            if (all.get(i).getFormName().equals(formName)) {
                return ResultUtil.error("保存失败，表单名重复！");
            }
        }
        return ResultUtil.success("保存成功");
    }

    @RequestMapping(value = "/updateVerify", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "保存时校验")
    public Result<Object> updateVerify(String formName, String id) {
        List<HkFormEntity> byFromName = hkFormEntityService.findByFromName(formName);
        if (byFromName.size() != 0) {
            for (int i = 0; i < byFromName.size(); i++) {
                if (byFromName.get(i).getFormName().equals(formName) && byFromName.get(i).getId().equals(id)) {
                    return ResultUtil.success("保存成功");
                } else if (byFromName.size() < 1) {
                    return ResultUtil.success("保存成功");
                } else if (!byFromName.get(i).getId().equals(id)) {
                    return ResultUtil.error("保存失败，表单名重复！");
                }
            }
        }

        return ResultUtil.success("保存成功！");
    }

    @RequestMapping(value = "/saveFormIndex", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增指标项")
    public Result saveFormIndex(HkFormEntity entity) {

        String[] formItemIds = entity.getFormItemIds();

        for (int i = 0; i < formItemIds.length; i++) {
            HkFormRelationShip ship = new HkFormRelationShip();
            ship.setFormId(entity.getId());
            ship.setItemId(formItemIds[i]);
            ship.setSortNumber(i + 1);
            hkFormRelationShipService.save(ship);
        }
        return ResultUtil.success("保存成功！");
    }
}
